package com.TeaManage.servlet;

import com.TeaManage.bean.Order;
import com.TeaManage.bean.OrderItem;
import com.TeaManage.bean.Customer;
import com.TeaManage.bean.Tea;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(name = "OrderServlet", urlPatterns = "/OrderServlet")
public class OrderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            // 添加订单
            String customerId = request.getParameter("customer_id");
            String totalAmountStr = request.getParameter("total_amount");
            String status = request.getParameter("status");
            
            // 验证必填字段
            if (customerId == null || customerId.trim().isEmpty() ||
                totalAmountStr == null || totalAmountStr.trim().isEmpty()) {
                request.setAttribute("error", "客户和订单金额不能为空");
                loadCustomersAndTeas(request);
                request.getRequestDispatcher("/views/order/addOrder.jsp").forward(request, response);
                return;
            }
            
            try {
                int customerIdInt = Integer.parseInt(customerId);

                Double totalAmount = Double.parseDouble(totalAmountStr);
                int statusInt = status != null ? Integer.parseInt(status) : 0;

                // 生成订单号
                String orderNo = generateOrderNo();
                
                String sql = "INSERT INTO `orders`(order_no, customer_id, total_amount, status, payment_time) VALUES(?, ?, ?, ?, ?)";
                Date paymentTime = statusInt == 1 ? new Date() : null;
                int result = GokJDBCUtil.update(sql, orderNo, customerIdInt, totalAmount, statusInt, paymentTime);
                
                if (result > 0) {
                    response.sendRedirect("OrderServlet");
                }
                
            } catch (NumberFormatException e) {
                request.setAttribute("error", "数据格式不正确");
                loadCustomersAndTeas(request);
                request.getRequestDispatcher("/views/order/addOrder.jsp").forward(request, response);
            }
            
        } else if ("toAdd".equals(action)) {
            // 跳转到新增页面
            loadCustomersAndTeas(request);
            request.getRequestDispatcher("/views/order/addOrder.jsp").forward(request, response);
            
        } else if ("deleteById".equals(action)) {
            // 删除订单
            int id = Integer.parseInt(request.getParameter("id"));
            
            // 先删除订单项
            String deleteItemsSql = "DELETE FROM order_item WHERE order_id = ?";
            GokJDBCUtil.update(deleteItemsSql, id);
            
            // 再删除订单
            String sql = "DELETE FROM `orders` WHERE order_id = ?";
            int result = GokJDBCUtil.update(sql, id);
            response.sendRedirect("OrderServlet");
            
        } else if ("findById".equals(action)) {
            // 查找订单用于查看详情
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "SELECT o.order_id, o.customer_id, o.order_no, o.total_amount, o.status, o.payment_time, c.customer_name FROM `orders` o LEFT JOIN customer c ON o.customer_id = c.customer_id WHERE o.order_id = ?";
            Order order = GokJDBCUtil.queryForObject(sql, Order.class, id);
            
            // 获取订单项
            String itemSql = "SELECT oi.*, t.tea_name FROM order_item oi LEFT JOIN tea t ON oi.tea_id = t.tea_id WHERE oi.order_id = ?";
            List<OrderItem> orderItems = GokJDBCUtil.queryAll(itemSql, OrderItem.class, id);
            
            request.setAttribute("order", order);
            request.setAttribute("orderItems", orderItems);
            request.getRequestDispatcher("/views/order/orderDetail.jsp").forward(request, response);
            
        } else if ("updateStatus".equals(action)) {
            // 更新订单状态
            int id = Integer.parseInt(request.getParameter("id"));
            int status = Integer.parseInt(request.getParameter("status"));
            
            String sql;
            if (status == 1) { // 已支付
                sql = "UPDATE `orders` SET status = ?, payment_time = ? WHERE order_id = ?";
                GokJDBCUtil.update(sql, status, new Date(), id);
            } else {
                sql = "UPDATE `orders` SET status = ? WHERE order_id = ?";
                GokJDBCUtil.update(sql, status, id);
            }
            
            response.sendRedirect("OrderServlet");
            
        } else if ("search".equals(action)) {
            // 搜索订单
            String orderNo = request.getParameter("orderNo");
            String customerName = request.getParameter("customerName");
            String statusStr = request.getParameter("status");
            
            // 分页参数
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT o.order_id, o.customer_id, o.order_no, o.total_amount, o.status, o.payment_time, c.customer_name FROM `orders` o LEFT JOIN customer c ON o.customer_id = c.customer_id WHERE 1=1");
            List<Object> params = new ArrayList<>();
            
            if (orderNo != null && !orderNo.trim().isEmpty()) {
                sql.append(" AND o.order_no LIKE ?");
                params.add("%" + orderNo + "%");
            }
            if (customerName != null && !customerName.trim().isEmpty()) {
                sql.append(" AND c.customer_name LIKE ?");
                params.add("%" + customerName + "%");
            }
            if (statusStr != null && !statusStr.trim().isEmpty()) {
                sql.append(" AND o.status = ?");
                params.add(Integer.parseInt(statusStr));
            }
            
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            
            // 添加分页
            sql.append(" ORDER BY o.order_id DESC LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            
            List<Order> orderList = GokJDBCUtil.queryAll(sql.toString(), Order.class, params.toArray());
            
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            
            // 返回结果
            request.setAttribute("orderList", orderList);
            request.setAttribute("orderNo", orderNo);
            request.setAttribute("customerName", customerName);
            request.setAttribute("status", statusStr);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/order/order.jsp").forward(request, response);
            
        } else {
            // 默认显示订单列表
            loadOrderList(request, response);
        }
    }
    
    private void loadOrderList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            page = 1;
            pageSize = 10;
        }
        
        // 查询总数
        String countSql = "SELECT COUNT(*) FROM `orders`";
        int total = GokJDBCUtil.queryForCount(countSql);
        System.out.println("total: " + total);
        
        // 查询数据 - 逐步测试字段
        String sql = "SELECT o.order_id, o.customer_id, o.order_no, o.total_amount, o.status, o.payment_time, c.customer_name FROM `orders` o LEFT JOIN customer c ON o.customer_id = c.customer_id ORDER BY o.order_id DESC LIMIT ?, ?";
        System.out.println("Executing SQL: " + sql);
        System.out.println("Parameters: " + (page-1)*pageSize + ", " + pageSize);
        List<Order> orderList = GokJDBCUtil.queryAll(sql, Order.class, (page-1)*pageSize, pageSize);
        System.out.println("orderList: " + orderList);
        
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        
        request.setAttribute("orderList", orderList);
        request.setAttribute("page", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("views/order/order.jsp").forward(request, response);
    }
    
    private void loadCustomersAndTeas(HttpServletRequest request) {
        // 获取客户列表
        String customerSql = "SELECT * FROM customer WHERE status = 1";
        List<Customer> customerList = GokJDBCUtil.queryAll(customerSql, Customer.class);
        request.setAttribute("customerList", customerList);
        
        // 获取茶叶列表
        String teaSql = "SELECT * FROM tea";
        List<Tea> teaList = GokJDBCUtil.queryAll(teaSql, Tea.class);
        request.setAttribute("teaList", teaList);
    }
    
    private String generateOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return "ORD" + sdf.format(new Date()) + String.format("%03d", (int)(Math.random() * 1000));
    }
}
